<!-- 用户气泡容器 -->
<template>
  <BubblesPanel position="left"
                width="360px"
                max-width="360px"
                :duration="200"
                :data="{nickname: renderValues.nickname}"
                :refresh="refresh"
                :click-fn="bubblesClickHandler">
    <template #container>
      <slot name="container" :avatar="avatar" :nickname="nickname" :desc="desc"></slot>
    </template>
    <template #bubbles>
      <div class="user-card relative p-3">
        <!-- 自己生成的 div -->
        <div>
          <a href="javasrcipt:" style="text-decoration: none;">
            <ImgTextAvatar class="avatar-mid"
                           height="77px"
                           width="77px"
                           :image="renderValues.avatar"
                           :label="renderValues.nickname"></ImgTextAvatar>
            <!--            <div class="avatar-mid"
                             :style="`background-image: url(${renderValues.avatar});`"></div>-->
          </a>
          <div class="user-card__meta">
            <div class="fn__ellipsis">
              <a href="javascript:" class="user-card__name"><b></b></a>
              <a href="javascript:" class="ft-gray ft-smaller">
                <b>{{ renderValues.nickname }}</b>
              </a>
            </div>
            <div class="user-card__info vditor-reset mt-2">
              <span class="ft-gray">
                {{ renderValues.desc }}
              </span>
            </div>
            <div class="user-card__icons flex mt-2">
              <div class="flex flex-1 ft-gray justify-content-start align-content-center">
                <i class="pi pi-users" style="color: var(--gray-500)">
                </i>
                <div class="inline-block" style="margin-left: 2px;">
                  {{ renderValues.fansCount }}
                </div>
              </div>
              <div v-if="props.nickname !== userMsg?.nickname"
                   class="fn__shrink justify-content-end align-content-end align-items-end">
                <a href="javascript:"
                   class="flex p-1 justify-content-center align-items-center align-content-center green small btn"
                   style="border-radius: 5px; text-decoration: none;">聊天</a>
                <button
                    class="flex p-1 justify-content-center align-items-center align-content-center small btn focus__btn"
                    style="background-color: rgb(0,0,0, 0); border: 1px solid rgb(209, 213, 218);border-radius: 5px;">
                  {{ renderValues.focus ? '取消关注' : '关注' }}
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>
  </BubblesPanel>

</template>

<script lang="ts" setup>
/** JS */
import {ref, reactive, defineProps, watch, defineEmits, inject} from 'vue';
import {UserService, UserMsg} from '@/utils/ApiRequest';
import Cache from '@/utils/Cache';
import {ExecFunction} from '@/utils/YzjUtils';
import toast from '@/utils/Toast';
/** 组件 */
import BubblesPanel from '@/components/panel/BubblesPanel.vue';
import ImgTextAvatar from '@/components/avatar/ImgTextAvatar.vue';


const $ = require('jquery'),
    cache = new Cache(),
    execFunction = new ExecFunction(),
    showChatDialog = inject('showChatDialog');
const userMsg: UserMsg = cache.get('userMsg');

const userService = new UserService();


const props = defineProps<{
      nickname: string
      desc: string
      avatar: string
      focus?: boolean
      fansCount?: number
    }>(),
    renderValues = reactive({
      nickname: props.nickname,
      desc: props.desc,
      avatar: props.avatar,
      focus: props.focus,
      fansCount: props.fansCount
    }),
    emits = defineEmits(['userFocus']);
watch(props, (n) => {
      Object.assign(renderValues, n)
    }, {deep: true}
);
const refresh = ref(false);
let oldTargetText = '', oldFansCount = 0;
/**
 * Tips 按钮操作
 * @param obj tips返回的对象
 */
const bubblesClickHandler = async (obj) => {
  let {event, data} = obj;
  let target: HTMLElement = event.target, innerText = target.innerText;
  if (target.nodeName === 'A' && innerText.trim() === '聊天') {
    // 打开聊天室
    showChatDialog();
  } else if (target.nodeName === 'BUTTON' && innerText.indexOf('关注') !== -1) {
    // 点击关注
    let $target = $(target),
        fansEle = $target.parent().siblings().children(':last-child');
    oldTargetText = target.innerText;
    oldFansCount = fansEle.text();
    let recordData = {text: oldTargetText, count: oldFansCount};
    // 修改粉丝
    if (oldTargetText.indexOf('关注') !== -1) {
      // 记录回滚值
      execFunction.record(recordData);
      // 阻塞 fn
      execFunction.blockageFunction(async () => {
        // 直接更改
        if (!renderValues.focus) {
          target.innerText = '取消关注';
          if (renderValues.fansCount !== undefined) {
            fansEle.text(renderValues.fansCount + 1)
          }
        } else {
          target.innerText = '关注';
          if (renderValues.fansCount !== undefined) {
            fansEle.text(renderValues.fansCount - 1)
          }
        }
        // 回滚 fn
        let result = await execFunction.exec(async () => {
          let res = await userService.update({
            focus: data.nickname
          });
          if (res) {
            let lastFocus = res.data.toFocus;
            if (lastFocus) {
              toast.success('关注成功', `很高兴你能在这里找到喜欢的人呢~(￣▽￣)"`, 3000)
            } else {
              toast.warn('取关成功', `世上又多了一个失去粉丝的人呢~/(ㄒoㄒ)/~~`, 3000)
            }
            emits('userFocus', {nickname: data.nickname, isFocus: lastFocus});
          }
        })
        // 如果 result 存在则进行回滚
        if (result) {
          target.innerText = result.text;
          fansEle.text(result.count);
        }
      }, (time) => {
        toast.error('捏🐎🐎滴~~', `点这么快干嘛哟？请${(time / 1000).toFixed(2)}秒后重试~~混蛋🤬`, 3000)
      }, 1500);
    }
  }
}

</script>

<style lang="less" scoped>

</style>
